import {$get} from '../../utils/ajax'
// pages/index/index.js
Page({
  // 计算总价
  clacTotalPrice() {
    let money = 0
    this.data.shoplist.forEach(r => {
      if (r.checked) {
        money += r.count * r.price
      }
    })
    this.setData({
      totalPrice: money
    })
  },
  // 勾选商品
  select(e) {
    let id = e.currentTarget.dataset.id
    let good = this.data.shoplist.find(r => r.id === id)
    good.checked = !good.checked

    let isSelectedAll = this.data.shoplist.every(r => r.checked)

    this.setData({
      shoplist: this.data.shoplist,
      isSelectedAll
    })
    this.clacTotalPrice()

  },
  // 全选商品
  selectAll() {
    this.data.isSelectedAll = !this.data.isSelectedAll
    this.data.shoplist.forEach(r => {
      r.checked = this.data.isSelectedAll
    })
    this.setData({
      isSelectedAll: this.data.isSelectedAll,
      shoplist: this.data.shoplist
    })
    this.clacTotalPrice()

  },
  // 商品数量 加
  add(e) {
    let id = e.currentTarget.dataset.id
    let goods = this.data.shoplist.find(r =>
      r.id === id
    )
    goods.count++
    this.setData({
      shoplist:this.data.shoplist
    })
    this.clacTotalPrice()
  },
  // 商品数量减
  jian(e) {
    let id = e.currentTarget.dataset.id
    let goods = this.data.shoplist.find(r =>
      r.id === id
    )
    if (--goods.count < 1) {
      goods.count = 1
    }
    this.setData({
      shoplist:this.data.shoplist
    })
    this.clacTotalPrice()

  },
  /**
   * 页面的初始数据
   */
  data: {
    totalPrice: 0,
    shoplist:[],
    isSelectedAll: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async getShopList(){
    let {shoplist} = await $get('/shoplist')
    this.setData({
      shoplist
    })
  },
  onLoad: function (options) {
    this.getShopList()
    this.clacTotalPrice()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})